package com.example.xianji.fragment;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.activity.Main_LoginActivity;
import com.example.xianji.activity.Main_SearchActivity;
import com.example.xianji.activity.Main_Send_XuQiuActivity;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.ErJi_FuWuFenlei_Adapter;
import com.example.xianji.adapter.FuWu_FenLei_Adapter;
import com.example.xianji.adapter.PlaceAdapter;
import com.example.xianji.adapter.XuQiu_Adapter;
import com.example.xianji.BGARefresh.BGANormalRefreshViewHolder;
import com.example.xianji.BGARefresh.BGARefreshLayout;
import com.example.xianji.BGARefresh.BGARefreshLayout.BGARefreshLayoutDelegate;
import com.example.xianji.bean.Place;
import com.example.xianji.bean.XuQiu;
import com.example.xianji.bean.YiJi_Class;

import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 需求大厅
 * @author me
 *
 */
public class XuQiuFragment extends Fragment implements OnClickListener,
		BGARefreshLayoutDelegate {
	/****************************** 需求大厅 **********************************/
	private BGARefreshLayout xuqiu_RefreshLayout;
	private ListView xuqiu_my_listview;
	private XuQiu_Adapter mXuQiu_Adapter;// 需求列表适配器
	private ArrayList<Integer> list;
	private ImageView xuqiu_search, xuqiu_image_load;
	// private CustomProgressDialog mCustomProgressDialog;
	private ArrayList<XuQiu> xuqiu_list = new ArrayList<XuQiu>();
	private int page = 1;
	private LinearLayout layout, layout1;
	private PopupWindow show_popupWindow;
	private ListView yiji_listview, erji_listview;//需求分类一级listview 和二级listview
	private FuWu_FenLei_Adapter mFuWu_FenLei_Adapter;//需求大厅 ：需求分类一级适配器
	private ErJi_FuWuFenlei_Adapter mErJi_FuWuFenlei_Adapter;//需求大厅 ：需求分类二级适配器
	private ArrayList<YiJi_Class> fenlei_list = new ArrayList<YiJi_Class>();//一级数据分类集合
	private ArrayList<YiJi_Class> erji_fenlei_list = new ArrayList<YiJi_Class>();//二级分类数据集合

	private LinearLayout linearlayout_fenlei, linear_layout_total,
			linearlayout_content, xuqiu_linearlayout_listview;
	private TextView text_hangye_fenlei, text_province_name, text_status,
			want_title;
	public Boolean erji_flag = false, province_click_flag = false,
			status_click_flag = false;
	public int erji_id = 0;
	public String fuwu_name = "需求分类", status_name = "全部", province_name = "地区",
			province_id = "";
	private GridView xuqiu_province_gridview;
	private PlaceAdapter mPlaceAdapter;
	private ArrayList<Place> province_list = new ArrayList<Place>();
	private RelativeLayout relativelayout_place, relativelayout_status;
	private ArrayList<Place> status_list = new ArrayList<Place>();
	private RelativeLayout relativeLayout_xuqiu_title;
	private View view;
	private AnimationDrawable xuqiu_animation;
	private View xuqiu_translation_view;
	private String url = "http://ht.cdn.turner.com/nba/big/channels/nba_tv/2016/04/02/20160402-bop-warriors-celtics.nba_nba_1280x720.mp4";
	private String url2 = "http://mediadownloads.mlb.com/mlbam/2009/05/09/mlbtv_tbabos_4494731_1m.mp4";
	public static String text_xuqiu_content = "";// 记录需求大厅的搜索关键词
	private RelativeLayout relativelayout_send_xuqiu_liebiao;
	//	private SharedPreferences sp;
//	private Editor ed;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 1) {
				xuqiu_my_listview.setAdapter(mXuQiu_Adapter);

				xuqiu_RefreshLayout.endRefreshing();

				xuqiu_animation.stop();

				xuqiu_image_load.setVisibility(View.GONE);

			}

			if (msg.what == 2) {
				mXuQiu_Adapter.notifyDataSetChanged();
				xuqiu_RefreshLayout.endLoadingMore();

			}

			if (msg.what == 4) {
				erji_listview.setAdapter(mErJi_FuWuFenlei_Adapter);
				erji_listview.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						hide();
						text_hangye_fenlei.setText(erji_fenlei_list.get(arg2)
								.getName());
						erji_id = erji_fenlei_list.get(arg2).getId();
						if (show_popupWindow != null) {
							show_popupWindow.dismiss();
							show_popupWindow = null;
						}
						fuwu_name = erji_fenlei_list.get(arg2).getName();
						erji_flag = true;
						get_xuqiu_data();
					}
				});
			}
		}

	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.xuqiu_layout, container, false);
		init();
		setListener();
		processLogic(savedInstanceState);
		return view;
	}

	private void init() {
		xuqiu_RefreshLayout = (BGARefreshLayout) view
				.findViewById(R.id.xuqiu_RefreshLayout);
		xuqiu_my_listview = (ListView) view
				.findViewById(R.id.xuqiu_my_listview);
		xuqiu_search = (ImageView) view.findViewById(R.id.xuqiu_search);
		linearlayout_fenlei = (LinearLayout) view
				.findViewById(R.id.linearlayout_fenlei);
		text_hangye_fenlei = (TextView) view
				.findViewById(R.id.text_hangye_fenlei);
		relativelayout_place = (RelativeLayout) view
				.findViewById(R.id.relativelayout_place);
		linear_layout_total = (LinearLayout) view
				.findViewById(R.id.linear_layout_total);
		text_province_name = (TextView) view
				.findViewById(R.id.text_province_name);
		relativelayout_status = (RelativeLayout) view
				.findViewById(R.id.relativelayout_status);
		text_status = (TextView) view.findViewById(R.id.text_status);
		want_title = (TextView) view.findViewById(R.id.want_title);
		relativeLayout_xuqiu_title = (RelativeLayout) view
				.findViewById(R.id.relativeLayout_xuqiu_title);
		xuqiu_image_load = (ImageView) view.findViewById(R.id.xuqiu_image_load);
		xuqiu_animation = (AnimationDrawable) xuqiu_image_load.getDrawable();
		xuqiu_animation.start();
		xuqiu_linearlayout_listview = (LinearLayout) view
				.findViewById(R.id.xuqiu_linearlayout_listview);
		relativelayout_send_xuqiu_liebiao = (RelativeLayout) view
				.findViewById(R.id.relativelayout_send_xuqiu_liebiao);
//		sp = getActivity().getSharedPreferences("text",
//				getActivity().MODE_PRIVATE);
//		ed = sp.edit();

		//xuqiu_animation.start();
		yiji_listview = (ListView) view.findViewById(R.id.xuqiu_yiji_listview);
		erji_listview = (ListView) view.findViewById(R.id.xuqiu_erji_listview);
		xuqiu_province_gridview = (GridView) view
				.findViewById(R.id.xuqiu_province_gridview);
		xuqiu_translation_view = view.findViewById(R.id.xuqiu_translation_view);
		
		mXuQiu_Adapter = new XuQiu_Adapter(getActivity(), xuqiu_list);
		XJApplication.cachThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				get_xuqiu_data();
			}
		});
	}

	private void setListener() {
		xuqiu_RefreshLayout.setDelegate(this);
		xuqiu_search.setOnClickListener(this);
		text_hangye_fenlei.setOnClickListener(this);
		// 省份点击
		relativelayout_place.setOnClickListener(this);
		linear_layout_total.setOnClickListener(this);
		relativelayout_status.setOnClickListener(this);
		xuqiu_translation_view.setOnClickListener(this);
		relativelayout_send_xuqiu_liebiao.setOnClickListener(this);
	}

	private void processLogic(Bundle savedInstanceState) {
		xuqiu_RefreshLayout
				.setRefreshViewHolder(new BGANormalRefreshViewHolder(
						getActivity(), true));
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		Log.i("OnCreat需求大厅需求大厅需求大厅", "OnCreat需求大厅需求大厅需求大厅");
	

		if (text_xuqiu_content.length() > 0) {
			want_title.setText(text_xuqiu_content);

		} else {

			want_title.setText("需求大厅");
		}

		text_hangye_fenlei.setText(fuwu_name);
		text_province_name.setText(province_name);
		text_status.setText(status_name);


	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.xuqiu_search) {

			Intent intent = new Intent(getActivity(), Main_SearchActivity.class);
			intent.putExtra("search", 1);
			startActivity(intent);

		}
		/**
		 * 需求分类点击
		 */
		else if (v.getId() == R.id.text_hangye_fenlei) {
			listview_show();
			mFuWu_FenLei_Adapter = new FuWu_FenLei_Adapter(getActivity(),
					fenlei_list);
			mErJi_FuWuFenlei_Adapter = new ErJi_FuWuFenlei_Adapter(
					getActivity(), erji_fenlei_list, 2);

			yiji_listview.setAdapter(mFuWu_FenLei_Adapter);

			yiji_listview.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					final int a = arg2;
					XJApplication.cachThreadPool.execute(new Runnable() {

						@Override
						public void run() {
							get_erji_fuwu_feilei(fenlei_list.get(a).getId());
						}
					});

					mFuWu_FenLei_Adapter.setPosition(arg2);
					mFuWu_FenLei_Adapter.notifyDataSetChanged();

				}
			});

		}
		/**
		 * 省份点击
		 *//*
		else if (v.getId() == R.id.relativelayout_place) {

			gridview_show();
			mPlaceAdapter = new PlaceAdapter(getActivity(), province_list, 2);

			xuqiu_province_gridview.setAdapter(mPlaceAdapter);

			xuqiu_province_gridview
					.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int arg2, long arg3) {

							hide();
							province_id = province_list.get(arg2).getArea_id();

							text_province_name.setText(province_list.get(arg2)
									.getArea_name());
							province_name = province_list.get(arg2)
									.getArea_name();

							province_click_flag = true;

							get_xuqiu_data();
						}
					});

		}*/

		/**
		 * 行业状态点击
		 *//*
		else if (v.getId() == R.id.relativelayout_status) {
			gridview_show();

			status();

			xuqiu_province_gridview.setAdapter(mPlaceAdapter);
			// background_alpha(0.5f);
			// status_flag=true;
			xuqiu_province_gridview
					.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int arg2, long arg3) {
							hide();
							status_name = status_list.get(arg2).getArea_name();

							text_status.setText(status_list.get(arg2)
									.getArea_name());

							status_click_flag = true;

							get_xuqiu_data();
						}
					});

		}*/ else if (v.getId() == R.id.xuqiu_translation_view) {

			hide();
		} else if (v.getId() == R.id.relativelayout_send_xuqiu_liebiao) {
			if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
				startActivity(new Intent(getActivity(),
						Main_Send_XuQiuActivity.class));
			} else {
				startActivity(new Intent(getActivity(),
						Main_LoginActivity.class));
			}

		}
	}

	private void gridview_show() {
		xuqiu_linearlayout_listview.setVisibility(View.GONE);
		xuqiu_province_gridview.setVisibility(View.VISIBLE);
		xuqiu_translation_view.setVisibility(View.VISIBLE);
	}

	protected void hide() {
		xuqiu_linearlayout_listview.setVisibility(View.GONE);
		xuqiu_province_gridview.setVisibility(View.GONE);
		xuqiu_translation_view.setVisibility(View.GONE);

		refresh_load_stop();
	}

	private void refresh_load_stop() {
		xuqiu_RefreshLayout.endRefreshing();
		xuqiu_RefreshLayout.endLoadingMore();
	}

	private void listview_show() {
		xuqiu_linearlayout_listview.setVisibility(View.VISIBLE);
		xuqiu_province_gridview.setVisibility(View.GONE);
		xuqiu_translation_view.setVisibility(View.VISIBLE);
	}

	public void get_xuqiu_data() {
		HttpUtils httpUtils = new HttpUtils();
		RequestParams parms = new RequestParams();

		parms.addBodyParameter("page", 1 + "");
		parms.addBodyParameter("k", text_xuqiu_content);

		parms.addBodyParameter("category", erji_id + "");
		parms.addBodyParameter("area", province_id);

		if (status_name.equals("全部")) {
			parms.addBodyParameter("status", "");
		} else if (status_name.equals("已发布")) {

			parms.addBodyParameter("status", "release");
		}

		else if (status_name.equals("已完成")) {
			parms.addBodyParameter("status", "finish");

		}

		httpUtils.send(HttpMethod.POST, Contant.xuqiu_liebiao, parms,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// handler.sendEmptyMessage(1);
						xuqiu_animation.stop();
						xuqiu_image_load.setVisibility(View.GONE);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							JSONObject response = new JSONObject(arg0.result);
							if (response.getInt("status") == 1) {
								xuqiu_list.clear();
								JSONArray array = response.getJSONArray("data");
								JSONArray ay = array.getJSONArray(0);
								JSONArray ay1 = array.getJSONArray(1);
								JSONArray ay2 = array.getJSONArray(2);
								if (ay.length() > 0) {
									for (int i = 0; i < ay.length(); i++) {
										JSONObject object = ay.getJSONObject(i);
										XuQiu mXuQiu = new XuQiu();
										mXuQiu.setTitle(object
												.getString("title"));
										mXuQiu.setBudget(object
												.getString("budget"));
										mXuQiu.setBudget_val(object
												.getString("budget_val"));
										mXuQiu.setId(object.getString("id"));
										if (i == 1 || i == 3 || i == 5
												|| i == 7) {
											mXuQiu.setUrl(url);
										} else {

											mXuQiu.setUrl(url2);
										}
										xuqiu_list.add(mXuQiu);
									}
								} else {
									Toast.makeText(getActivity(), "暂无数据", Toast.LENGTH_LONG)
											.show();
								}
								fenlei_list.clear();
								for (int i = 0; i < ay1.length(); i++) {
									JSONObject obj = ay1.getJSONObject(i);
									YiJi_Class mYiJi_Class = new YiJi_Class();
									mYiJi_Class.setId(obj.getInt("id"));
									mYiJi_Class.setName(obj.getString("name"));
									fenlei_list.add(mYiJi_Class);

								}
								province_list.clear();
								for (int i = 0; i < ay2.length(); i++) {
									JSONObject obj1 = ay2.getJSONObject(i);
									Place mYiJi_Class = new Place();
									mYiJi_Class.setArea_id(obj1
											.getInt("area_id") + "");
									mYiJi_Class.setArea_name(obj1
											.getString("area_name"));
									province_list.add(mYiJi_Class);
								}

								handler.sendEmptyMessage(1);
							} else {
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	public void get_xuqiu_data_more() {
		/*
		 * HashMap<String, Object> map=new HashMap<String, Object>();
		 * 
		 * 
		 * map.put("page",page+"");
		 * 
		 * map.put("k",Main_SearchActivity.text_xuqiu_content);
		 * 
		 * if(erji_flag){ map.put("category",erji_id);
		 * 
		 * }
		 * 
		 * if(province_click_flag){ map.put("area",province_id); }
		 * if(status_click_flag){ if(status_name.equals("全部")){
		 * map.put("status",""); }else if(status_name.equals("已发布")){
		 * 
		 * map.put("status","release"); }
		 * 
		 * else if(status_name.equals("已完成")){ map.put("status","finish");
		 * 
		 * 
		 * 
		 * }
		 * 
		 * }
		 */

		HttpUtils httpUtils = new HttpUtils();
		RequestParams parms = new RequestParams();
		parms.addBodyParameter("page", page + "");
		parms.addBodyParameter("k", text_xuqiu_content);
		parms.addBodyParameter("category", erji_id + "");
		parms.addBodyParameter("area", province_id + "");
		if (status_name.equals("全部")) {
			parms.addBodyParameter("status", "");
		} else if (status_name.equals("已发布")) {
			parms.addBodyParameter("status", "release");
		}
		else if (status_name.equals("已完成")) {
			parms.addBodyParameter("status", "finish");
		}
		httpUtils.send(HttpMethod.POST, Contant.xuqiu_liebiao, parms,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// handler.sendEmptyMessage(1);
						xuqiu_animation.stop();
						xuqiu_image_load.setVisibility(View.GONE);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							JSONObject response = new JSONObject(arg0.result);
							if (response.getInt("status") == 1) {
								JSONArray array = response.getJSONArray("data");

								JSONArray ay = array.getJSONArray(0);
								if (ay.length() > 0) {
									for (int i = 0; i < ay.length(); i++) {
										JSONObject object = ay.getJSONObject(i);
										XuQiu mXuQiu = new XuQiu();
										mXuQiu.setTitle(object
												.getString("title"));
										mXuQiu.setBudget(object
												.getString("budget"));
										mXuQiu.setBudget_val(object
												.getString("budget_val"));
										mXuQiu.setId(object.getString("id"));
										xuqiu_list.add(mXuQiu);
									}
								} else {
									Toast.makeText(getActivity(), "没有更多数据", Toast.LENGTH_LONG)
											.show();
								}
								handler.sendEmptyMessage(2);
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	/**
	 * 二级服务分类
	 * @param id
	 */
	public void get_erji_fuwu_feilei(int id) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("cid", id);
		JSONObject params = new JSONObject(map);

		JsonObjectRequest request = new JsonObjectRequest(Method.POST,
				Contant.xuqiu_fenlei, params, new Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject response) {
						try {
							if (response.getInt("status") == 1) {
								erji_fenlei_list.clear();
								JSONArray array = response.getJSONArray("data");
								JSONArray array1 = array.getJSONArray(0);
								for (int i = 0; i < array1.length(); i++) {
									JSONObject object = array1.getJSONObject(i);
									YiJi_Class mYiJi_Class = new YiJi_Class();
									mYiJi_Class.setId(object.getInt("id"));
									mYiJi_Class.setName(object
											.getString("name"));
									erji_fenlei_list.add(mYiJi_Class);
								}
								handler.sendEmptyMessage(4);

							} else {
								Toast.makeText(getActivity(),
										response.getString("msg"), Toast.LENGTH_SHORT).show();
							/*	if (MainActivity.mCustomProgressDialog != null) {
									MainActivity.mCustomProgressDialog
											.dismiss();

									MainActivity.mCustomProgressDialog = null;
								}*/
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
					}
				});
		XJApplication.getHttpQueues().cancelAll("abcPost");
		request.setTag("abcPost");
		request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
		XJApplication.getHttpQueues().add(request);
		XJApplication.getHttpQueues().start();
	}

	/**
	 * 状态数据
	 */
	public void status() {
		status_list.clear();
		Place mYiJi_Class = new Place();
		Place mYiJi_Class1 = new Place();
		Place mYiJi_Class2 = new Place();
		mYiJi_Class.setArea_name("全部");
		mYiJi_Class1.setArea_name("已发布");
		mYiJi_Class2.setArea_name("已完成");
		status_list.add(mYiJi_Class);
		status_list.add(mYiJi_Class1);
		status_list.add(mYiJi_Class2);
		mPlaceAdapter = new PlaceAdapter(getActivity(), status_list, 2);

	}

	@Override
	public void onResume() {
		super.onResume();

		if (text_xuqiu_content.length() > 0) {
			want_title.setText(text_xuqiu_content);

		} else {

			want_title.setText("需求大厅");
		}

		if (Main_SearchActivity.xuqiu_search_id == 1) {
			XJApplication.cachThreadPool.execute(new Runnable() {

				@Override
				public void run() {
					get_xuqiu_data();
				}
			});

			Main_SearchActivity.xuqiu_search_id = 0;
		}
		refresh_load_stop();
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden) {

			new Handler() {

				@Override
				public void handleMessage(Message msg) {
					super.handleMessage(msg);
					xuqiu_RefreshLayout.endRefreshing();
					xuqiu_RefreshLayout.endLoadingMore();
				}

			}.sendEmptyMessage(0);
		}
	}

	@Override
	public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
		if (xuqiu_animation.isVisible()) {
			xuqiu_RefreshLayout.endRefreshing();
		} else {
			XJApplication.cachThreadPool.execute(new Runnable() {

				@Override
				public void run() {
					page = 1;
					get_xuqiu_data();
				}
			});
		}
	}

	@Override
	public boolean onBGARefreshLayoutBeginLoadingMore(
			BGARefreshLayout refreshLayout) {
		page++;
		XJApplication.cachThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				get_xuqiu_data_more();
			}
		});

		return true;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		handler.removeCallbacksAndMessages(null);
		text_xuqiu_content = "";
	}
}
